package my.app.timer;

import android.media.MediaPlayer;
import android.os.Handler;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class SeekBarUpdate 
{
	public Handler mHandler = new Handler();
	public SeekBar seekbar;
    public MediaPlayer player;
    public SeekBarUpdate(final MediaPlayer mp,SeekBar bar)
	{
		seekbar=bar;
		player=mp;	
		seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
		{
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) 
			{
				if(fromTouch)
				{
				mHandler.removeCallbacks(mUpdateTimeTask);
				
				player.seekTo(progress);
				seekbar.setProgress(progress);
				}
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) 
			{
				// remove message Handler from updating progress bar
				mHandler.removeCallbacks(mUpdateTimeTask);
			}
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) 
			{
				mHandler.removeCallbacks(mUpdateTimeTask);
				
				player.seekTo(seekBar.getProgress());

				// update timer progress again
				updateProgressBar();
			}
		});
	}
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() 
		   {
			   seekbar.setMax(player.getDuration());
			   seekbar.setProgress(player.getCurrentPosition());
		       mHandler.postDelayed(this, 50);
		   }
		};

	public void updateProgressBar() 
	{
        mHandler.postDelayed(mUpdateTimeTask, 50);
    }	

}
